import { useState, useRef, useEffect } from 'react'
import { useParams, Link } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { 
  Send, 
  ArrowLeft, 
  Stethoscope, 
  Bot, 
  User,
  Loader2
} from 'lucide-react'
import { ChatAPI } from '@/services/api'
import { useAuth } from '@/contexts/auth-context'
import { useToast } from '@/hooks/use-toast'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import 'highlight.js/styles/github.css'

interface Message {
  id: string
  content: string
  sender: 'user' | 'ai'
  timestamp: Date
}

export default function ChatPage() {
  const { type } = useParams<{ type: string }>()
  const [messages, setMessages] = useState<Message[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [currentAIMessage, setCurrentAIMessage] = useState('')
  const scrollAreaRef = useRef<HTMLDivElement>(null)
  const eventSourceRef = useRef<EventSource | null>(null)
  const { isLoggedIn } = useAuth()
  const { toast } = useToast()

  // 生成唯一的聊天ID
  const chatId = useRef<string>(`chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`)

  const agentInfo = {
    medical: {
      name: '医疗智能体',
      icon: Stethoscope,
      color: 'from-blue-500 to-blue-600',
      description: '我是您的专业灵溪医疗助手，可以帮助您分析症状、提供健康建议。'
    },
    super: {
      name: '超级智能体',
      icon: Bot,
      color: 'from-green-500 to-green-600',
      description: '我是全能型AI助手，可以帮助您解决各种问题和任务。'
    }
  }

  const currentAgent = agentInfo[type as keyof typeof agentInfo] || agentInfo.medical

  useEffect(() => {
    // 初始欢迎消息
    const welcomeMessage: Message = {
      id: '1',
      content: `您好！${currentAgent.description}请问有什么可以帮助您的吗？`,
      sender: 'ai',
      timestamp: new Date()
    }
    setMessages([welcomeMessage])
    
    // 进入聊天界面时滚动到顶部
    setTimeout(() => {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }, 100)
  }, [type])

  // 滚动到底部的函数
  const scrollToBottom = () => {
    if (scrollAreaRef.current) {
      const scrollElement = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]')
      if (scrollElement) {
        scrollElement.scrollTop = scrollElement.scrollHeight
      } else {
        // 备用方案
        scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight
      }
    }
  }

  // 当消息变化时自动滚动到底部
  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 当AI消息实时更新时也滚动到底部
  useEffect(() => {
    if (currentAIMessage) {
      scrollToBottom()
    }
  }, [currentAIMessage])

  const handleSendMessage = async () => {
    if (!inputValue.trim() || isLoading) return

    // 检查登录状态
    if (!isLoggedIn) {
      toast({
        title: "请先登录",
        description: "需要登录后才能使用聊天功能",
        variant: "destructive"
      })
      return
    }

    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputValue,
      sender: 'user',
      timestamp: new Date()
    }

    const messageContent = inputValue
    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)
    setCurrentAIMessage('')

    try {
      // 根据智能体类型选择不同的SSE接口
      let eventSource: EventSource
      
      if (type === 'medical') {
        eventSource = ChatAPI.createMedicalChatStream(messageContent, chatId.current)
      } else {
        eventSource = ChatAPI.createSuperAgentStream(messageContent, chatId.current)
      }

      eventSourceRef.current = eventSource

      // 处理SSE消息
      eventSource.onmessage = (event) => {
        console.log('SSE message received:', event.data) // 调试日志
        
        try {
          const data = JSON.parse(event.data)
          
          if (data.content) {
            setCurrentAIMessage(prev => {
              const newMessage = prev + data.content
              // 延迟滚动，确保DOM更新完成
              setTimeout(() => scrollToBottom(), 50)
              return newMessage
            })
          }
        } catch (error) {
          console.error('Failed to parse SSE data:', error)
          // 如果不是JSON格式，直接添加文本内容
          setCurrentAIMessage(prev => {
            const newMessage = prev + event.data
            setTimeout(() => scrollToBottom(), 50)
            return newMessage
          })
        }
      }

      // 处理连接打开
      eventSource.onopen = () => {
        console.log('SSE connection opened')
      }

      // 处理连接错误或结束
      eventSource.onerror = (error) => {
        console.error('SSE error:', error)
        
        // 将当前累积的AI消息添加到消息列表
        if (currentAIMessage) {
          const aiResponse: Message = {
            id: (Date.now() + 1).toString(),
            content: currentAIMessage,
            sender: 'ai',
            timestamp: new Date()
          }
          setMessages(prev => [...prev, aiResponse])
        }
        
        setCurrentAIMessage('')
        setIsLoading(false)
        eventSource.close()
        eventSourceRef.current = null
        
        toast({
          title: "连接已结束",
          description: "AI响应完成",
        })
      }

    } catch (error) {
      console.error('Failed to create SSE connection:', error)
      setIsLoading(false)
      
      toast({
        title: "连接失败",
        description: error instanceof Error ? error.message : "无法连接到AI服务",
        variant: "destructive"
      })
    }
  }

  // 清理SSE连接
  useEffect(() => {
    return () => {
      if (eventSourceRef.current) {
        eventSourceRef.current.close()
        eventSourceRef.current = null
      }
    }
  }, [])

  // 当currentAIMessage变化时，更新消息列表中的最后一条AI消息
  useEffect(() => {
    if (currentAIMessage && isLoading) {
      setMessages(prev => {
        const newMessages = [...prev]
        const lastMessage = newMessages[newMessages.length - 1]
        
        // 如果最后一条消息是AI消息且正在加载中，更新它
        if (lastMessage && lastMessage.sender === 'ai' && lastMessage.id === 'temp-ai') {
          lastMessage.content = currentAIMessage
        } else {
          // 否则添加新的临时AI消息
          newMessages.push({
            id: 'temp-ai',
            content: currentAIMessage,
            sender: 'ai',
            timestamp: new Date()
          })
        }
        
        return newMessages
      })
    }
  }, [currentAIMessage, isLoading])

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const Icon = currentAgent.icon

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-green-50 p-4">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <Card className="mb-4 border-0 bg-white/80 backdrop-blur-sm">
          <CardHeader className="pb-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <Link to="/">
                  <Button variant="ghost" size="icon">
                    <ArrowLeft className="w-5 h-5" />
                  </Button>
                </Link>
                <div className={`w-12 h-12 bg-gradient-to-r ${currentAgent.color} rounded-xl flex items-center justify-center`}>
                  <Icon className="w-6 h-6 text-white" />
                </div>
                <div>
                  <CardTitle className="text-xl">{currentAgent.name}</CardTitle>
                  <p className="text-sm text-gray-600">在线 • 随时为您服务</p>
                </div>
              </div>
            </div>
          </CardHeader>
        </Card>

        {/* Chat Area */}
        <Card className="h-[600px] flex flex-col border-0 bg-white/80 backdrop-blur-sm">
          <ScrollArea className="flex-1 p-4" ref={scrollAreaRef}>
            <div className="space-y-4">
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`flex ${message.sender === 'user' ? 'justify-end' : 'justify-start'}`}
                >
                  <div className={`flex items-start space-x-2 max-w-[80%] ${message.sender === 'user' ? 'flex-row-reverse space-x-reverse' : ''}`}>
                    <Avatar className="w-8 h-8">
                      <AvatarFallback className={message.sender === 'user' ? 'bg-blue-100' : 'bg-gray-100'}>
                        {message.sender === 'user' ? (
                          <User className="w-4 h-4" />
                        ) : (
                          <Icon className="w-4 h-4" />
                        )}
                      </AvatarFallback>
                    </Avatar>
                    <div
                      className={`rounded-2xl px-4 py-2 ${
                        message.sender === 'user'
                          ? 'bg-gradient-to-r from-blue-600 to-blue-700 text-white'
                          : 'bg-gray-100 text-gray-900'
                      }`}
                    >
                      <div className="prose prose-sm max-w-none">
                        <ReactMarkdown
                          remarkPlugins={[remarkGfm]}
                          rehypePlugins={[rehypeHighlight]}
                          components={{
                            // 自定义样式
                            p: ({children}) => <p className="mb-2 last:mb-0">{children}</p>,
                            code: ({inline, children, ...props}) => 
                              inline ? (
                                <code className="bg-gray-200 px-1 py-0.5 rounded text-xs" {...props}>
                                  {children}
                                </code>
                              ) : (
                                <pre className="bg-gray-200 p-2 rounded text-xs overflow-x-auto my-2">
                                  <code {...props}>{children}</code>
                                </pre>
                              ),
                            ul: ({children}) => <ul className="list-disc list-inside mb-2">{children}</ul>,
                            ol: ({children}) => <ol className="list-decimal list-inside mb-2">{children}</ol>,
                            li: ({children}) => <li className="mb-1">{children}</li>,
                            h1: ({children}) => <h1 className="text-lg font-bold mb-2">{children}</h1>,
                            h2: ({children}) => <h2 className="text-base font-bold mb-2">{children}</h2>,
                            h3: ({children}) => <h3 className="text-sm font-bold mb-1">{children}</h3>,
                            blockquote: ({children}) => <blockquote className="border-l-4 border-gray-300 pl-3 italic mb-2 text-gray-600">{children}</blockquote>,
                            table: ({children}) => <table className="border-collapse border border-gray-300 mb-2 text-xs">{children}</table>,
                            th: ({children}) => <th className="border border-gray-300 px-2 py-1 bg-gray-100 font-bold text-left">{children}</th>,
                            td: ({children}) => <td className="border border-gray-300 px-2 py-1">{children}</td>,
                            strong: ({children}) => <strong className="font-bold">{children}</strong>,
                            em: ({children}) => <em className="italic">{children}</em>,
                            a: ({children, href}) => <a href={href} className="text-blue-600 hover:underline" target="_blank" rel="noopener noreferrer">{children}</a>,
                          }}
                        >
                          {message.content}
                        </ReactMarkdown>
                      </div>
                      <p className={`text-xs mt-1 ${message.sender === 'user' ? 'text-blue-100' : 'text-gray-500'}`}>
                        {message.timestamp.toLocaleTimeString()}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
              
              {isLoading && (
                <div className="flex justify-start">
                  <div className="flex items-start space-x-2">
                    <Avatar className="w-8 h-8">
                      <AvatarFallback className="bg-gray-100">
                        <Icon className="w-4 h-4" />
                      </AvatarFallback>
                    </Avatar>
                    <div className="bg-gray-100 rounded-2xl px-4 py-2">
                      <div className="flex items-center space-x-2">
                        <Loader2 className="w-4 h-4 animate-spin" />
                        <span className="text-gray-600">正在思考中...</span>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </ScrollArea>

          {/* Input Area */}
          <div className="border-t p-4">
            <div className="flex space-x-2">
              <Input
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="输入您的问题..."
                className="flex-1"
                disabled={isLoading}
              />
              <Button 
                onClick={handleSendMessage}
                disabled={!inputValue.trim() || isLoading}
                className="bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800"
              >
                <Send className="w-4 h-4" />
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  )
}